import ajax from '../main.js';
import '../../css/systemManage/myself.scss'



layui.use(['form', 'laydate', 'upload'], function () {
    var form = layui.form, $ = layui.$;
    var laydate = layui.laydate;
    var upload = layui.upload;


    let userInfo = JSON.parse(localStorage.userInfo);
    let [{ IDnumber, age, avatar, _id, education, phone, role, sex, uname, into_time, write_time }] = userInfo;
    form.val("update-form", {
        uname,
        role,
        phone,
        write_time,
        sex,
        age,
        education,
        IDnumber,
        into_time
    });

    // 给头像 src 赋值
    $('#avatar_img').attr('src', avatar);
    $('#nav_avatar').html(`
        <img src="${avatar}" class="layui-nav-img">${uname}
    `)
    laydate.render({
        elem: '#write_time', //指定元素
    });
    laydate.render({
        elem: '#into_time', //指定元素
    });

    // 更换头像
    var uploadInst = upload.render({
        elem: '#update_avatar',  //绑定元素
        url: 'http://localhost:3000/users/upload', //上传接口
        auto: false,
        bindAction: '#submitBtn',
        choose: function (obj) {
            //预读本地文件示例，不支持ie8
            obj.preview(function (index, file, result) {
                console.log(result);
                $('#avatar_img').attr('src', result); //图片链接（base64）
            });
        },
        done:function(res){
            console.log(res.path);
            avatar = res.path;
            console.log(avatar);
        }
    });

    $('#submitBtn').click(function(){
        setTimeout(function(){
            let data = form.val("update-form");
            data.avatar = avatar;

            (async function(){
                console.log(1);
                const result = await ajax({
                    url:'/users/' + _id,
                    type:'PUT',
                    data
                })
                if(result.code == 200){
                    alert('修改成功')
                    console.log(result.data);
                    localStorage.userInfo = JSON.stringify(result.data);
                    location.reload();
                }
                
            })()
            
        },100)
        
    })
})

